package com.whc.orders.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.whc.api.client.GoodsClient;
import com.whc.api.client.PayClient;
import com.whc.api.dto.GoodsCreateDto;

import com.whc.api.dto.OrderAndGoodsDto;
import com.whc.api.dto.OrderDto;
import com.whc.api.dto.PayApplyDTO;
import com.whc.common.constant.RabbitMqConstant;
import com.whc.common.domain.DelayMessage;
import com.whc.orders.domain.entity.OrderAndGoods;
import com.whc.orders.domain.entity.Orders;
import com.whc.orders.mapper.OrderAndGoodsMapper;
import com.whc.orders.mapper.OrdersMapper;
import com.whc.orders.service.OrdersService;
import com.whc.common.domain.Result;
import com.whc.common.utils.SnowflakeIdGenerator;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;



@Service
public class OrderServiceImpl implements OrdersService {
    private final SnowflakeIdGenerator snowflakeId=new SnowflakeIdGenerator(0,0);
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderAndGoodsMapper orderAndGoodsMapper;
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private PayClient payClient;
    @Resource
    private RabbitTemplate rabbitTemplate;



    @Override
    //添加订单，以及减库存，添加支付单
    @GlobalTransactional(name = "create-order",rollbackFor = Exception.class)
    public Long addOrder(OrderDto orderDto) {
        Orders order=new Orders();
        BeanUtils.copyProperties(orderDto,order);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setStatus(1); //未付款

        //随便生成的订单号
        long orderNum=snowflakeId.generateId();
        order.setOrderNumber(orderNum);

        //绑定订单号和商品的关系
        double cot=0;
        List<Long> ids=new ArrayList<>();
        Map<Long,Long> map=new HashMap<>();
        for(OrderAndGoodsDto detailDTO:orderDto.getDetail()){
                ids.add(detailDTO.getGoodsId());
                map.put(detailDTO.getGoodsId(),detailDTO.getNumber());

            OrderAndGoods orderAndGoods = new OrderAndGoods();
            orderAndGoods.setGoodsId(detailDTO.getGoodsId());
            orderAndGoods.setOrderNumber(orderNum);
            orderAndGoods.setSellerId(detailDTO.getSellerId());
            orderAndGoods.setNumber(detailDTO.getNumber());

            orderAndGoodsMapper.insert(orderAndGoods);
        }

        //生成支付单
        PayApplyDTO payApplyDTO = new PayApplyDTO();
        payApplyDTO.setAmount(cot);
        payApplyDTO.setOrderNumber(orderNum);
        payClient.addPay(payApplyDTO);

        //计算总报价
        Result<List<GoodsCreateDto>> goodsResult = goodsClient.selectByIds(ids);
        for(GoodsCreateDto o:goodsResult.getData()){
            cot+=o.getPrice()*map.get(o.getId());
        }
        order.setAccountTotal(cot);

//        //支付单的生成的异步调用
//
//        try {
//            rabbitTemplate.convertAndSend("orders.topic","add.orders",payApplyDTO);
//        }catch (Exception e){
//            e.printStackTrace();
//            System.out.println("rabbitMq调用出现异常啦！");
//        }

        //减库存
        goodsClient.deductGoodsByIds(orderDto);

        //添加订单
        ordersMapper.insert(order);


        DelayMessage<Long> delayMessage = DelayMessage.of(order.getId(), 1000L, 2000L,5000L,10000L,20000L);
        //发送延迟消息如果超时未处理就取消订单
        rabbitTemplate.convertAndSend(RabbitMqConstant.DELAY_EXCHANGE,
                RabbitMqConstant.DELAY_ORDER_ROUTING_KEY,delayMessage,
                message -> {
                    message.getMessageProperties().setDelay(delayMessage.removeNextDelay().intValue());
                    return message;
                });
        return orderNum;
    }

    //修改订单为已支付
    @Override
    public void toPayOrder(Long orderNumber) {
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_number",orderNumber);
        //修改为已支付
        updateWrapper.set("status",1);
        updateWrapper.set("pay_time",LocalDateTime.now());
        ordersMapper.update(updateWrapper);
    }

    //取消订单还没写，远程调用商品微服务实现库存恢复
    @Override
    public void cancelOrder(Long orderNumber) {
        //修改订单状态
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_number",orderNumber);
        //修改为已取消
        updateWrapper.set("status",5);
        updateWrapper.set("update_time",LocalDateTime.now());
        ordersMapper.update(updateWrapper);

        //恢复库存
        List<OrderAndGoodsDto> orderAndGoodsDtos = orderAndGoodsMapper.selectGoodsByOrderNumber(orderNumber);
        OrderDto orderDto = new OrderDto();
        orderDto.setDetail(orderAndGoodsDtos);
        goodsClient.resetGoodsByIds(orderDto);
    }

    @Override
    public List<Orders> selectUserAll(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("buyer_id",userId);
        List<Orders> list = ordersMapper.selectList(queryWrapper);
        System.out.println(list);
        return list;
    }

    @Override
    public List<OrderAndGoodsDto> selectGoodsByOrderNumber(Long orderNumber) {
        if(orderNumber==null){
            throw new RuntimeException("订单编号为空");
        }
        return orderAndGoodsMapper.selectGoodsByOrderNumber(orderNumber);
    }

    @Override
    public List<Orders> selectAll() {
        List<Orders> orders = ordersMapper.selectList(null);
        return orders;
    }


}
